package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.JGColor;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.engineer.activity.QuestionActivity;
import com.asktgapp.eventbus.EngineerPassEvent;
import com.asktgapp.eventbus.HasNewEvent;
import com.asktgapp.hxsg.BiuEaseHelper;
import com.asktgapp.model.ChatRecordVO;
import com.asktgapp.model.FreeAskSearchVO;
import com.asktgapp.model.PayConsultItemVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.EngineerDetailActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.utils.EaseCommonUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/2/1
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class PayConsultItemFragment extends BaseFragment {
    private RefreshRecyclerView mRefreshRecyclerView;
    private BaseAdapter mBaseAdapter;
    private RecyclerView mRecyclerView;
    private int mPage = 1;
    private int type = 0; //0 当前咨询， 1 历史咨询
    private Apiservice mApiservice;
    private TextView mNewMsg;
    private int mZXType;
    private LinearLayout noData;

    //
    public static PayConsultItemFragment newInstance(int type) {
        PayConsultItemFragment fragment = new PayConsultItemFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        Log.i("type", "newInstance:type= " + type);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void showNoData() {
        noData.setVisibility(View.VISIBLE);
        noData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
            }
        });
        mRefreshRecyclerView.setVisibility(View.GONE);
    }

    public void hideNoData() {
        noData.setVisibility(View.GONE);
        mRefreshRecyclerView.setVisibility(View.VISIBLE);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_consult_item, container, false);
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        Bundle bundle = getArguments();
        type = bundle.getInt("type");
        Log.i("type", "getArguments:type= " + type);
        mApiservice = ApiUtil.getInstance().create();
        mRefreshRecyclerView = rootView.findViewById(R.id.recycle);
        mRecyclerView = mRefreshRecyclerView.getRecyclerView();
        mNewMsg = rootView.findViewById(R.id.tv_has_new_msg);
        noData = rootView.findViewById(R.id.ll_no);
        mRefreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage++;
                getData();
            }
        });
        mRefreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getData();
            }
        });
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {

                //工程师和普通用户共用的当前咨询fragment
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_consult, parent, false), new BaseViewHolder.Callbacks() {
                    @Override
                    public void bind(BaseViewHolder holder, Object data) {
                        if (data instanceof PayConsultItemVO) {
                            final PayConsultItemVO bean = (PayConsultItemVO) data;
                            ImageView imageView = holder.getView(R.id.iv_head_engineer);
                            TextView tvMsgTime = holder.getView(R.id.tvMsgTime);
                            TextView lable = holder.getView(R.id.tv_lable);
                            TextView msgNumber = holder.getView(R.id.msgNumber);
                            TextView addTime = holder.getView(R.id.tvTime);

                            if (bean.getUnreadMsg() > 0) {
                                msgNumber.setVisibility(View.VISIBLE);
                                msgNumber.setText(String.valueOf(bean.getUnreadMsg()));
                               if(type==0){
                                   if (!PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER))
                                       HasNewEvent.postEvent(1);
                                   else
                                       HasNewEvent.postEvent(6);
                               }
                            } else {
                                msgNumber.setVisibility(View.GONE);
                                if(type==0) {
                                    if (!PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER))
                                        HasNewEvent.postEvent(0);
                                    else
                                        HasNewEvent.postEvent(5);
                                }
                            }

                            ImageDisplayUtil.loadCircleHeadImage(getActivity(), imageView, bean.getUserPic());
                            holder.setText(R.id.tv_name, bean.getUserName());

                            //标签
//                            if (bean.getIsEngineer() == 1) {
//                                lable.setVisibility(View.VISIBLE);
//                            } else {
//                                lable.setVisibility(View.GONE);
//                            }
//                            String type = "";
//                            if (bean.getType() == 0) {
//                                type = "即时咨询 ";
//                            } else if (bean.getType() == 1) {
//                                type = getString(R.string.homePage_used_check);
//                            } else if (bean.getType() == 2) {
//                                type = getString(R.string.homePage_problem_check);
//                            }
                            imageView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (!PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
                                        Intent intent = new Intent(getActivity(), EngineerDetailActivity.class);
                                        intent.putExtra("id", String.valueOf(bean.getbUserId()));
                                        startActivity(intent);
                                    }
                                }
                            });

                            holder.setText(R.id.tv_content, bean.getLastContent());
                            if (type == 0) {
                                tvMsgTime.setText(bean.getTime());
                                addTime.setTextColor(JGColor.MSG_BG_RED);
                                if (!TextUtils.isEmpty(bean.getAddTime())) {
                                    long addLongTime = Util.getDateAfter(Util.StrToDate(bean.getAddTime(), "yyyy.MM.dd HH:mm:ss"), 1).getTime();

                                    String addStringTime = Util.hSec2Date(String.valueOf(addLongTime), "yyyy-MM-dd HH:mm:ss");

                                    String time;
                                    try {
                                        time = Util.getDistanceTimes(Util.getCurrentDate2(), addStringTime);
                                    } catch (ParseException e) {
                                        time = "未知";
                                        e.printStackTrace();
                                    }
                                    Log.e("eeee", "addLongTime:" + addLongTime + "\naddStringTime:" + addStringTime +
                                            "\nUtil.getCurrentDate2():" + Util.getCurrentDate2() + "\n time" + time);
                                    addTime.setText("剩余：" + time);

                                }

                            } else {
                                msgNumber.setVisibility(View.GONE);
                                tvMsgTime.setText("");
                                Date date = Util.StrToDate(bean.getAddTime(), "yyyy.MM.dd HH:mm:ss");
                                String timeStr = Utils.getAskTime(date);
                                addTime.setText(timeStr);
                                addTime.setTextColor(JGColor.APP_TEXT_SECOND);
                            }


                        }

                    }

                    @Override
                    public void onItemClick(View view, int position) {
                        //考虑 结束后看详情的情况
                        PayConsultItemVO bean = (PayConsultItemVO) mBaseAdapter.getData().get(position);
                        String huanXinId;

                        if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {//工程师
                            huanXinId = bean.getOrdinaryHuanId();
                            if (Util.isEmpty(huanXinId)) {
                                showTost("对方不在线", 1);
                                return;
                            }
                            int newType = 2;
                            if (type == 1)//历史咨询
                                newType = 3;//工程师进入历史咨询
                            BiuEaseHelper
                                    .getInstance()
                                    .beginSingleChat(getActivity(), "", huanXinId
                                            , bean.getUserName()
                                            , bean.getUserPic(), bean.getUserId() + ""
                                            , newType, bean.getId() + "", 0);
                        } else {
                            huanXinId = bean.getEngineerHuanId();
                            if (Util.isEmpty(huanXinId)) {
                                showTost("对方不在线", 1);
                                return;
                            }

                            BiuEaseHelper
                                    .getInstance()
                                    .beginSingleChat(getActivity(), "", huanXinId
                                            , bean.getUserName()
                                            , bean.getUserPic(), bean.getbUserId() + ""
                                            , type, bean.getId() + "", 0);
                        }
                    }
                });
                return holder;
            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setAdapter(mBaseAdapter);

    }


    @Override
    public void loadData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        mPage = 1;
        getData();
    }


    private void setUI(List<PayConsultItemVO> list, boolean addAll) {

//        List list = new ArrayList();//如果要剔除获取不到记录的对话则放开这行与①，注释掉②
        String mHXID = PreferencesUtil.getString(getActivity(), PreferencesUtil.KEY_HX_ID);
        EMClient.getInstance().chatManager().loadAllConversations();
        for (PayConsultItemVO bean : list) {
            String huanXinId;
            if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER))
                huanXinId = bean.getOrdinaryHuanId();
            else
                huanXinId = bean.getEngineerHuanId();

            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(huanXinId, EaseCommonUtils.getConversationType(EaseConstant.CHATTYPE_SINGLE), false);


            if (conversation != null) {
                List<EMMessage> msgs = conversation.getAllMessages();
                Collections.reverse(msgs);
                EMMessage last = null;

                for (int i = 0; i < msgs.size(); i++) {
                    EMMessage l = msgs.get(i);
                    if (l.getFrom().equals(mHXID) || l.getTo().equals(mHXID)) ;
                    last = l;
                    break;
                }

                if (last != null) {
                    bean.setUnreadMsg(conversation.getUnreadMsgCount());
                    Log.i("EMConversation", last.toString());
                    if (last.getType() == EMMessage.Type.TXT) {
                        String s = last.getBody().toString().replace("txt:", "").replaceAll("\"", "");
                        bean.setLastContent(s);
                    } else if (last.getType() == EMMessage.Type.VOICE) {
                        bean.setLastContent("[语音]");
                    } else if (last.getType() == EMMessage.Type.IMAGE) {
                        bean.setLastContent("[图片]");
                    }

                    Log.e("eee", bean.getLastContent());
                    if (last.direct() == EMMessage.Direct.SEND) {
                        bean.setRepeat(false);
                    }
                    if (last.direct() == EMMessage.Direct.RECEIVE) {
                        bean.setRepeat(true);
                    }
                    Date date = new Date();
                    date.setTime(last.getMsgTime());
                    bean.setTime(Utils.getAskTime(date));
//                list.add(bean);//①
                } else {
                    Log.i("EMConversation", "null");
                }
            }
        }
        if (type == 0) {

        }
        if (addAll) {
            mBaseAdapter.addData(BaseAdapter.AddType.LASE, list);
        } else {
            mBaseAdapter.setData(list);                                                     //②
        }
        //mRefreshRecyclerView.showNextMore(mPage);

//        mBaseAdapter.setData(recordVO.getUserList());//①
//        if (type == 0 || type == 2) {
//            if (hasnew) {
//                HasNewEvent.postEvent(1);
//            } else {
//                HasNewEvent.postEvent(0);
//            }
//        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFresh(EngineerPassEvent event) {
        if (event.getType()) {
            mPage = 1;
            getData();
        }

    }

    private void getData() {
//    isEnd    是否结束
        if (Util.isEmpty(PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID)))
            return;
        HashMap params = new HashMap();
        params.put("userId", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("page", mPage);
        params.put("isEnd", type);
        if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
            params.put("isEngineer", 1);
        } else {
            params.put("isEngineer", 0);
        }

        Apiservice apiservice = ApiUtil.getInstance().create();
        Call<ApiResponseBody<List<PayConsultItemVO>>> call = apiservice.selMyOrderList(params);
        call.enqueue(new Callback<ApiResponseBody<List<PayConsultItemVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<PayConsultItemVO>>> call, Response<ApiResponseBody<List<PayConsultItemVO>>> response) {
                inVisibleLoading();
                if (mRefreshRecyclerView == null) {
                    Log.i("JGAPP", "mRefreshRecyclerView == null");
                    return;
                }
                Log.i("JGAPP", " 调用了接口");
                mRefreshRecyclerView.endPage();
                if (response.isSuccessful()) {
                    List<PayConsultItemVO> mDataList = response.body().getResult();

                    if (mPage == 1) {
                        if (mDataList == null || mDataList.size() == 0) {
                            showNoData();
                            if(type==0){
                                if (!PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER))
                                    HasNewEvent.postEvent(0);
                                else
                                    HasNewEvent.postEvent(5);
                            }
                        } else {
                            hideNoData();
                            setUI(mDataList, false);
                        }
                    } else {
                        if (mDataList == null || mDataList.size() == 0) {
                            mRefreshRecyclerView.showNoMore();
                        } else {
                            setUI(mDataList, true);
                        }
                    }
                } else {
                    showNoData();
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<PayConsultItemVO>>> call, Throwable t) {
                inVisibleLoading();
                if (mRefreshRecyclerView == null) {
                    Log.i("JGAPP", "mRefreshRecyclerView == null");
                    return;
                }
                Log.i("JGAPP", " 调用了接口");
                mRefreshRecyclerView.endPage();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });

    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
